<template>
  <div class="progress-container">
    <el-card class="progress-card">
      <template #header>
        <div class="card-header">
          <h3>案件进度管理</h3>
          <el-button type="primary" @click="handleAdd">新增进度</el-button>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" @submit.prevent="handleQuery">
        <el-form-item label="案件">
          <el-input v-model="queryForm.case_id" placeholder="请输入案件编号搜索案件" clearable />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="queryForm.keywords" placeholder="进度内容" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="progressList" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="case_code" label="案件编号" min-width="120" />
        <el-table-column prop="event_type" label="事件类型" width="100">
          <template #default="{ row }">
            {{ getEventTypeText(row.event_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="进度内容" min-width="200" />
        <el-table-column prop="operator_name" label="操作人" width="120" />
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <!-- 当进度内容包含"挂起"或"取消挂起"时，不显示删除按钮 -->
            <el-button
              v-if="!row.content.includes('挂起') && !row.content.includes('取消挂起')"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="案件" prop="case_id">
          <el-select
            v-model="form.case_id"
            placeholder="请选择案件"
            filterable
            remote
            :remote-method="searchCases"
            :loading="caseLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in caseOptions"
              :key="item.id"
              :label="item.case_code"
              :value="item.id"
            >
              <span style="float: left">{{ item.case_code }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.case_name }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件类型" prop="event_type">
          <el-select v-model="form.event_type" placeholder="请选择事件类型" style="width: 100%">
            <el-option :value="1" label="通知" />
            <el-option :value="2" label="进展" />
            <el-option :value="3" label="庭审" />
            <el-option :value="4" label="文书" />
            <el-option :value="5" label="任务" />
            <el-option :value="6" label="立案" />
            <el-option :value="7" label="提交材料" />
            <el-option :value="8" label="开庭" />
            <el-option :value="9" label="判决" />
            <el-option :value="10" label="执行" />
            <el-option :value="11" label="结案" />
            <el-option :value="12" label="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入进度内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useLawcaseStore } from '../../store/lawcase'
  import { getEventTypeText } from '../../constants/lawcase'
  import request from '@/utils/request'

  // 定义案件进度类型
  interface CaseProgress {
    id: number
    case_id: number
    case_code: string
    content: string
    operator: number
    operator_name: string
    create_time: string
    event_time: string
    event_type: number
  }

  // 定义案件类型
  interface Lawcase {
    id: number
    case_code: string
    case_name: string
  }

  // 数据列表
  const progressList = ref<CaseProgress[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 案件选项
  const caseOptions = ref<Lawcase[]>([])
  const caseLoading = ref(false)

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    case_id: '',
    keywords: '',
  })

  // 对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  // 表单数据
  const form = reactive({
    id: 0,
    case_id: '',
    content: '',
    event_type: 1,
    event_time: '',
  })

  // 表单验证规则
  const rules = {
    case_id: [{ required: true, message: '请选择案件', trigger: 'change' }],
    content: [{ required: true, message: '请输入进度内容', trigger: 'blur' }],
  }

  // 表单引用
  const formRef = ref()

  // 获取案件列表用于搜索
  const searchCases = async (query: string) => {
    caseLoading.value = true
    try {
      const res: any = await request.get('/api/lawcase/cases/list', {
        params: {
          page: 1,
          limit: 20,
          keywords: query,
        },
      })

      if (res.code === 0) {
        caseOptions.value = res.data
      }
    } catch (error) {
      console.error('搜索案件失败:', error)
    } finally {
      caseLoading.value = false
    }
  }

  // 获取数据列表
  const getProgressList = async () => {
    loading.value = true
    try {
      // 调用真实API
      const lawcaseStore = useLawcaseStore()
      const res: any = await lawcaseStore.getProgressListAction(queryForm)

      // 处理响应数据
      if (res.code === 0) {
        progressList.value = res.data
        total.value = res.count || 0
      } else {
        ElMessage.error(res.msg || '获取案件进度列表失败')
      }
    } catch (error: any) {
      console.error('API Error:', error)
      ElMessage.error(error.message || '获取案件进度列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查询
  const handleQuery = () => {
    queryForm.page = 1
    getProgressList()
  }

  // 重置
  const handleReset = () => {
    queryForm.case_id = ''
    queryForm.keywords = ''
    queryForm.page = 1
    getProgressList()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getProgressList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getProgressList()
  }

  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增案件进度'
    isEdit.value = false
    Object.assign(form, {
      id: 0,
      case_id: '',
      content: '',
      event_type: 1,
      event_time: '',
    })
    dialogVisible.value = true
  }

  // 编辑
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑案件进度'
    isEdit.value = true
    Object.assign(form, row)
    dialogVisible.value = true
  }

  // 删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除该案件进度吗？', '提示', {
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await request({
            url: '/api/lawcase/progresses/del',
            method: 'delete',
            data: { id: row.id },
          })
          if (res.code === 0) {
            ElMessage.success('删除成功')
            getProgressList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {})
  }

  // 提交表单
  const handleSubmit = () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          let res: any
          if (isEdit.value) {
            // 编辑案件进度
            res = await request.post('/api/lawcase/progresses/edit', {
              id: form.id,
              case_id: form.case_id,
              content: form.content,
              event_type: form.event_type,
              event_time: form.event_time || new Date().toISOString().slice(0, 10),
            })
          } else {
            // 新增案件进度
            res = await request.post('/api/lawcase/progresses/add', {
              case_id: form.case_id,
              content: form.content,
              event_type: form.event_type,
              event_time: form.event_time || new Date().toISOString().slice(0, 10),
            })
          }

          if (res.code === 0) {
            ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
            dialogVisible.value = false
            getProgressList()
          } else {
            ElMessage.error(res.msg || (isEdit.value ? '编辑失败' : '新增失败'))
          }
        } catch (error) {
          ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
        }
      }
    })
  }

  // 初始化
  onMounted(() => {
    getProgressList()
  })
</script>

<style scoped>
  .progress-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .progress-card {
    margin-bottom: 20px;
  }
</style>
